package com.tpc.pictool.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.List;
import javax.imageio.ImageIO;

import com.tpc.pictool.bean.PicBean;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Component;

@Component
public class PDFUtil {
    public PDFUtil() {
    }

    public static void pdfToImageFile(String fileName, Integer annexid) throws Exception {
        Connection connection = null;




        PDDocument doc = null;
        ByteArrayOutputStream os = null;
        InputStream stream = null;
        OutputStream out = null;
        try {
            connection = JDBCUtil.getConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "SELECT  * FROM KmAttachment a  where Annexid=?";
            System.out.println(sql);
            PicBean picBean = queryRunner.query(connection, sql, new BeanHandler<>(PicBean.class),annexid);

            stream = new FileInputStream(fileName);
            doc = PDDocument.load(stream);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            PDPageTree pages = doc.getPages();
            int pageCount = pages.getCount();
            String[] imgs = new String[pageCount];
            for(int i = 0; i < pageCount; ++i) {
                if (pageCount == 1) {
                    BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200.0F);
                    os = new ByteArrayOutputStream();
                    ImageIO.write(bim, "png", os);
                    byte[] dataList = os.toByteArray();
                    fileName = fileName.replaceAll(".pdf", ".png");
                    File file = new File(fileName);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    }
                    String updateSql = "update KmAttachment set filename=replace(filename,'.pdf','.png') where Annexid=?";
                    queryRunner.update(connection,updateSql,annexid);
                    out = new FileOutputStream(file);
                    out.write(dataList);
                }else{
                    int annexIdCode = CodeUtil.getAnnexIdCode(connection);
                    File file = new File(fileName);
                    String tempFileName = file.getName();
                    String tempFilePath = file.getParent();
                    BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200.0F);
                    os = new ByteArrayOutputStream();
                    ImageIO.write(bim, "png", os);
                    byte[] dataList = os.toByteArray();
                    tempFileName = annexIdCode+"_"+tempFileName.replaceAll(".pdf", ".png");

                    File tempFile = new File(tempFilePath+SystemUtil.getFileHyphen()+tempFileName);
                    if (!tempFile.getParentFile().exists()) {
                        tempFile.getParentFile().mkdirs();

                        tempFile.createNewFile();
                    }
                    imgs[i] = tempFile.getPath();
                    String insertSql = "insert into KmAttachment(annexid,refid,tbname,attachtype,filename,attachsize,placeid,offertime,ver,entid,beactive,billno,pictypeid) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    Object[] objects = new Object[13];
                    objects[0] = annexIdCode;
                    objects[1] = picBean.getRefId();
                    objects[2] = picBean.getTabName();
                    objects[3] = picBean.getAttachType();
                    objects[4] = picBean.getFileName();
                    objects[5] = picBean.getAttachSize();
                    objects[6] = picBean.getPlaceId();
                    objects[7] = picBean.getOfferTime();
                    objects[8] = picBean.getVer();
                    objects[9] = picBean.getEntId();
                    objects[10] = picBean.getBeactive();
                    objects[11] = picBean.getBillNo();
                    objects[12] = picBean.getPicTypeId();

                    queryRunner.update(connection,insertSql,objects);
                    String insertSqlLink = "insert into PicLink(refid,attachid,pictypeid,picname,entid) values {?,?,?,?,?}";
                    Object[] objectsLink = new Object[5];
                    objectsLink[0] = picBean.getRefId();
                    objectsLink[1] = annexIdCode+"_"+picBean.getFileName();
                    objectsLink[2] = picBean.getPicTypeId();
                    objectsLink[3] = picBean.getFileName();
                    objectsLink[4] = picBean.getEntId();
                    queryRunner.update(connection,insertSqlLink,objectsLink);
                    out = new FileOutputStream(tempFile);
                    out.write(dataList);
                }
            }
            if(pageCount>1){
                fileName = fileName.replaceAll(".pdf", ".png");
                ImageUtil.merge(imgs,"png",fileName);
                PNGResizeExample.pngResizeExample(fileName);
            }
        } catch (Exception var15) {
            var15.printStackTrace();
            throw var15;
        } finally {
            if (doc != null) {
                doc.close();
            }

            if (os != null) {
                os.close();
            }

            if (stream != null) {
                stream.close();
            }

            if (out != null) {
                out.close();
            }
            if(connection!=null){
                connection.close();
            }
        }

    }
}

